package com.example.server.command;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.naming.NamingException;

import org.eclipse.jetty.continuation.Continuation;

import com.example.server.ErrorConst;
import com.example.server.db.DBManager;
import com.example.server.message.Message;
import com.example.server.message.MessageFactory;
import com.example.server.message.ResultMessage;

public abstract class AbstractCommand {

	private Continuation continuation;
	protected Message msg;
	protected Map<String, String> msgMapping;

	public void run() {
		// 打开数据库connnection
		Connection conn = null;
		try {
			DBManager.getInstance().getConnection();
			doHander();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 关闭数据库connction
			DBManager.getInstance().releaseConnection();
			// 事务处理
		}

	}

	public abstract void doHander();

	protected void writeToJson(ResultMessage out) {
		String o = MessageFactory.toJson(out);
		continuation.getServletResponse().setContentType("application/json;charset=utf-8");
		try {
			continuation.getServletResponse().getWriter().write(o);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public ResultMessage getResultMessage(int result, Map<String, Object> info) {
		ResultMessage ret = new ResultMessage(msg);
		ret.setResult(result);
		ret.setError(ErrorConst.getError(result));
		Map<String, Object> out = new LinkedHashMap<String, Object>();
		MessageFactory.packInfo(info, out, msgMapping);
		ret.setInfo(out);
		return ret;
	}

	public Continuation getContinuation() {
		return continuation;
	}

	public void setContinuation(Continuation continuation) {
		this.continuation = continuation;
	}

}
